package com.itheima.pay.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.itheima.pay.config.AlipayConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Description:
 * @Version: V1.0
 */
@RestController
public class PayController {

    @Autowired
    AlipayConfig alipayConfig;

    @GetMapping("/alipaytest")
    public void alipaytest(HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws IOException {
        AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig.getURL(),
                alipayConfig.getAPPID(), alipayConfig.getRSA_PRIVATE_KEY(),
                alipayConfig.getFORMAT(), alipayConfig.getCHARSET(),
                alipayConfig.getALIPAY_PUBLIC_KEY(), alipayConfig.getSIGNTYPE());
        //获得初始化的AlipayClient   手机网站支付模式
        AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();
        //创建API对应的 request
        // 注意订单的唯一性
        alipayRequest.setBizContent("{" +
                "\"out_trade_no\":\"20210321210102123\","
                + " \"total_amount\":\"0.01\","
                + " \"subject\":\"Iphone6 16G\","
                + " \"product_code\":\"QUICK_WAP_PAY\""
                + " }");
        //填充业务参数   支付表单（html）
        String form = "";
        try {
            form = alipayClient.pageExecute(alipayRequest).getBody();
            System.out.println(form);
            //调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        httpResponse.setContentType("text/html;charset=" + alipayConfig.getCHARSET());
        httpResponse.getWriter().write(form);
        //直接将完整的表单html输出到页面
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
    }

}
